import router from '@/router'
import store from '@/store'
import asyncRoutes from './router/asyncRoutes'
const WhiteList = ['/login', '/404']

function getFirstPermission(permission) {
  // console.log(permission)
  // 筛选完之后拿出来第一个permission
  const firstPermissionArr = permission.map(item => {
    return item.split(':')[0]
  })
  // firstPermissionArr
  // set是一个伪数组,可以用来去除重复出现的数组
  return Array.from(new Set(firstPermissionArr))
}
function getSecondPermission(permission) {
  const secondPermission = permission.map(item => {
    // return item.split(':')[0]
    const arr = item.split(':')[0]
    return `${arr[0]}:${arr[1]}`
  })
  return Array.from(new Set(secondPermission))
}
function getRoutes(firstPermission, secondPermission, asyncRoutes) {
  const firstRoutes = asyncRoutes.filter(item => firstPermission.includes(item.permission))
  // console.log(firstRoutes)
  if (firstPermission.includes('*')) {
    return asyncRoutes
  }
  const routes = firstRoutes.map(item => {
    return {
      ...item,
      children: item.children.filter(child => { secondPermission.includes(child.permission) })
    }
  })
  // console.log(routes)
  return routes
}
// router  路由中的beforeEach
// 一般用在登录的时候验证是否有权限,如果没有的话就让调到登录页让登录
// beforeEach的钩子函数，它是一个全局的before 钩子函数， （before each）意思是在 每次每一个路由改变的时候都得执行一遍。
router.beforeEach(async(to, from, next) => {
  // to 是即将要进入的路由
  // from 是即将要离开的路由
  const token = store.state.user.token
  if (token) {
    // console.log(123)
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      // 1.拿到用户的权限信息
      const permission = await store.dispatch('menu/getUserPermission')
      // console.log(permission)
      // 2.根据权限信息标识,筛选出对应的一级路由标识
      const firstPermission = getFirstPermission(permission)
      // console.log(firstPermission)
      // 3.根据权限信息标识,筛选出对应的二级路由标识
      const secondPermission = getSecondPermission(permission)
      // console.log(secondPermission)
      // 根据一级权限标识和二级权限标识和动态路由标识进行筛选
      const routes = getRoutes(firstPermission, secondPermission, asyncRoutes)
      // console.log(asyncRoutes)
      // console.log(routes)
      routes.forEach(element => {
        return router.addRoute(element)
      })
      store.commit('menu/setmenuList', routes)
    }
  } else {
    // includes这个意思是如果includes中通往的路径中包含登录和404的
    if (WhiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
    // console.log(12322)
  }
  // next()
  // 在进行判断之前要先进行放行
})
